<template>
  <FCPage
    direction="row"
    class="paymentApplicationFormQuery"
  >
    <FCLayout :flex="1">
      <FCPage direction="column">
        <FCLayout>
          <!-- 付款申请单查询条件 -->
          <FCPage
            direction="column"
            class="backgroundColor marginBottom"
          >
            <FCLayout :flex="1">
              <FCForm
                ref="queryFormRef"
                v-bind="queryFormConfig"
                :collapseForm="queryFormCollapse"
                :dataset="queryDataSet"
                @change="handleFormChange"
              />
              <div
                class="marginTop"
                style="text-align: right"
              >
                <a-space>
                  <FCButton
                    type="primary"
                    :loading="loadingTable"
                    @click="getPaymentApplicationFormQueryData"
                  >查询</FCButton>
                  <FCButton @click="handleReset">重置</FCButton>
                  <FCButton
                    :loading="submitButtonFlag"
                    @click="handleSubmit"
                  >提交</FCButton>
                  <FCButton
                    :loading="exportFileButtonFlag"
                    @click="handleExportFile"
                  >导出</FCButton>
                  <FCButton
                    :disabled="nowRecord.paymentstatus !='7'"
                    @click="handlePaymentInfo"
                  >支付信息</FCButton>
                  <FCButton
                    :loading="downFileButtonFlag"
                    @click="handleDownFile"
                  >下载付款资料</FCButton>
                  <FCButton
                    @click="queryFormCollapse = !queryFormCollapse"
                    :value="queryFormCollapse ? '展开' : '收起'"
                    type="link"
                  >
                  </FCButton>
                </a-space>
              </div>
            </FCLayout>
          </FCPage>
        </FCLayout>
        <FCLayout
          :flex="1"
          class="backgroundColor"
        >
          <!-- table信息汇总 -->
          <FCPage
            direction="column"
            style="position: relative;"
          >
            <FCLayout
              :flex="1"
              class="marginBottom"
            >
              <FCTable
                :scroll="tableDataSource.length > 0 ? { x: '100%'} : { x: '100%'} "
                :fields="tableFields"
                :dataset="tableDataSet"
                :customRow="customRow"
                shouldSelect
                shouldPagination
                :rowKey="rowKey"
                :selectedRowKeys="selectedRowKeys"
                :onSelectChange="handleSelectChange"
                :loading="loadingTable || loadingPDF"
              />
              <!-- 付款申请单详情 -->
              <paymentApplicationFormInfo
                ref="paymentApplicationFormInfo"
                :detailData="tableDataSource[index]"
              />
            </FCLayout>
            <FCLayout
              height="36px"
              class="totalInfo"
              justifyContent="start"
            >
              <FCPage direction="row">
                <a-space>
                  已选择笔数：
                  <div
                    :title="editorsumnum"
                    class="numUnderline"
                  >{{editorsumnum}}</div>
                  已选择应付金额：
                  <div
                    :title="editorsumexchangeamount"
                    class="numUnderline"
                  >{{editorsumexchangeamount.toFixed(2)}}</div>元
                  已选择折币金额：
                  <div
                    :title="editorsumamount"
                    class="numUnderline"
                  >{{editorsumamount.toFixed(2)}}</div>元
                </a-space>
              </FCPage>
            </FCLayout>
          </FCPage>
        </FCLayout>
        <FCLayout>
          <!-- 行划盘支付 -->
          <paymentWay
            ref="paymentWay"
            :activeKey="activeKey"
            :nowRecordPaymentstatus="nowRecord.paymentstatus"
            :selectedRowsExchangecurrencycode="selectedRowsExchangecurrencycode"
            :selectedRows="selectedRows"
            :nowRecord="nowRecord"
            @paymentSuccess="handlePaymentSuccess"
            @cancelSelect="handleCancelSelect"
            @submitSuccess="handleSubmitSuccess"
          />
        </FCLayout>
      </FCPage>
    </FCLayout>
  </FCPage>
</template>

<script>
import FCDataset from '@/vendors/fc-dataset/FCDataset'
import FCPage from '@/layouts/FCPage.vue'
import FCLayout from '@/layouts/FCLayout.vue'
import FCForm from '@/vendors/fc-ui/src/form/FCForm.vue'
import FCTable from '@/vendors/fc-ui/src/table/FCTable.vue'
import FCButton from '@/vendors/fc-ui/src/controls/FCButton.vue'
import FCInput from '@/vendors/fc-ui/src/controls/FCInput.vue'
import paymentWay from './paymentWay'
import paymentApplicationFormInfo from './paymentApplicationFormInfo'

import {
  drp_paymentstatus,
  drop_fastflag,
  drp_currency,
  drop_payway,
  drop_domestic,
  drp_type,
} from '@/pages/paymentApplicationFormPay/data'
import {
  getPaymentApplicationFormQueryData,
  getDownPaymentFile,
  getExportFile,
  submitPaymentApplicationFormData,
  getPaymentViewPDF,
} from '@/apis/paymentApplicationFormApi'

export default {
  name: '',
  components: {
    FCPage,
    FCLayout,
    FCForm,
    FCTable,
    FCButton,
    FCInput,
    paymentWay,
    paymentApplicationFormInfo,
  },
  data() {
    const formDataSet = new FCDataset({
      fields: [
        { name: 'capitalallocationbillno', type: 'string' },
        { name: 'customername', type: 'string' },
        { name: 'summaryno', type: 'string' },
        { name: 'paymentstatus', type: 'string' },
        { name: 'fastflag', type: 'string' },
        { name: 'startdate', type: 'date' },
        { name: 'enddate', type: 'date' },
        { name: 'exchangecurrencycode', type: 'string' },
        { name: 'payway', type: 'string' },
        { name: 'custaccountarea', type: 'string' },
        { name: 'paymentmode', type: 'string' },
      ],
      datas: [
        {
          capitalallocationbillno: '',
          customername: '',
          summaryno: '',
          paymentstatus: '6',
          fastflag: '',
          startdate: null,
          enddate: null,
          exchangecurrencycode: '00',
          payway: '00',
          custaccountarea: '',
          paymentmode: '00',
        },
      ],
    })
    const tableDataSet = new FCDataset({
      fields: [
        { name: 'payway', type: 'string' },
        { name: 'capitalallocationbillno', type: 'string' },
        { name: 'summaryno', type: 'string' },
        { name: 'exchangecurrencycode', type: 'string' },
        { name: 'exchangeamount', type: 'number' },
        { name: 'currencycode', type: 'string' },
        { name: 'amount', type: 'number' },
        { name: 'operatetime', type: 'string' },
        { name: 'customercode', type: 'string' },
        { name: 'customername', type: 'string' },
        { name: 'paymentstatus', type: 'string' },
        { name: 'operratorname', type: 'string' },
        { name: 'fastflag', type: 'string' },
        { name: 'tabperiod', type: 'string' },
        { name: 'memo', type: 'string' },
        { name: 'paymenttime', type: 'date' },
        { name: 'in_amount', type: 'string' },
        { name: 'in_currency', type: 'string' },
        { name: 'paymentmode', type: 'string' },
        { name: 'viewPDF', type: 'string' },
        { name: 'accountname', type: 'string' },
        { name: 'inpaymentmethod', type: 'string' },
        { name: 'custaccountno', type: 'string' },
        { name: 'custbankno', type: 'string' },
        { name: 'bankname', type: 'string' },
        { name: 'bankprovince', type: 'string' },
        { name: 'bankcity', type: 'string' },
        { name: 'exchangeflag', type: 'string' },
        { name: 'exchangerate', type: 'string' },
        { name: 'bankaccountno', type: 'string' },
      ],
      datas: [],
    })
    return {
      rowKey: 'capitalallocationbillno',
      activeKey: '1',
      selectedRowsExchangecurrencycode: '',
      queryFormCollapse: false,
      exportFileButtonFlag: false,
      submitButtonFlag: false,
      downFileButtonFlag: false,
      paymentButtonFlag: true,
      selectedRows: [],
      selectedRowKeys: [],
      loadingTable: false,
      loadingPDF: false,
      tableDataSource: [],
      index: null,
      nowRecord: {},
      tableFields: [
        { type: 'selection', fixed: 'left', width: 40 },
        {
          title: '申请单类型',
          name: 'payway',
          width: 160,
          ellipsis: true,
          customRender: (text) => {
            return (
              drop_payway.filter((item) => item.value == text)[0]?.label ||
              '未知'
            )
          },
        },
        {
          title: '划拨申请单号',
          name: 'capitalallocationbillno',
          width: 200,
          ellipsis: true,
        },
        {
          title: '申请单编号',
          name: 'summaryno',
          width: 200,
          ellipsis: true,
          controlType: 'button',
          controlProps: {
            type: 'link',
            onClick: () => {
              this.handleOpenInfo()
            },
          },
        },
        {
          title: '应付币种',
          name: 'exchangecurrencycode',
          width: 160,
          ellipsis: true,
          customRender: (text) => {
            return (
              drp_currency.filter((item) => item.value == text)[0]?.label ||
              '未知'
            )
          },
        },
        {
          title: '应付金额',
          name: 'exchangeamount',
          width: 160,
          ellipsis: true,
        },
        {
          title: '折币币种',
          name: 'currencycode',
          width: 160,
          ellipsis: true,
          customRender: (text) => {
            return (
              drp_currency.filter((item) => item.value == text)[0]?.label ||
              '未知'
            )
          },
        },
        {
          title: '折币金额',
          name: 'amount',
          width: 160,
          ellipsis: true,
        },
        {
          title: '申请单递交日期',
          name: 'operatetime',
          width: 160,
          ellipsis: true,
        },
        {
          title: '再保人ID',
          name: 'customercode',
          width: 200,
          ellipsis: true,
        },
        {
          title: '再保人',
          name: 'customername',
          width: 160,
          ellipsis: true,
        },
        {
          title: '申请单状态',
          name: 'paymentstatus',
          width: 160,
          ellipsis: true,
          customRender: (text) => {
            return (
              drp_paymentstatus.filter((item) => item.value == text)[0]
                ?.label || '未知'
            )
          },
        },
        {
          title: '申请人',
          name: 'operratorname',
          width: 160,
          ellipsis: true,
        },
        {
          title: '加急件',
          name: 'fastflag',
          width: 80,
          ellipsis: true,
          customRender: (text) => {
            return (
              drop_fastflag.filter((item) => item.value == text)[0]?.label ||
              '未知'
            )
          },
        },
        {
          title: '查看PDF',
          name: 'viewPDF',
          width: 100,
          ellipsis: true,
          controlType: 'button',
          controlProps: {
            type: 'link',
            onClick: () => {
              this.handleOpenPDF()
            },
          },
        },
        {
          title: '账期',
          name: 'tabperiod',
          width: 160,
          ellipsis: true,
        },
        {
          title: '支付备注信息',
          name: 'memo',
          width: 160,
          ellipsis: true,
        },
        {
          title: '实际付款日期',
          name: 'paymenttime',
          width: 160,
          ellipsis: true,
        },
        {
          title: '付款金额',
          name: 'in_amount',
          width: 160,
          ellipsis: true,
        },
        {
          title: '付款币种',
          name: 'in_currency',
          width: 160,
          ellipsis: true,
          customRender: (text) => {
            return (
              drp_currency.filter((item) => item.value == text)[0]?.label ||
              '未知'
            )
          },
        },
        {
          title: '支付方式',
          name: 'paymentmode',
          width: 160,
          ellipsis: true,
          customRender: (text) => {
            return (
              drp_type.filter((item) => item.value == text)[0]?.label || '未知'
            )
          },
        },
      ],
      tableDataSet: tableDataSet,
      editorsumnum: 0,
      editorsumexchangeamount: 0,
      editorsumamount: 0,
      queryDataSet: formDataSet,
      queryFormConfig: {
        cols: 4, //每行布局几列
        labelCol: 8,
        wrapperCol: 16,
        labelAlign: 'right', //对齐方式
        fields: [
          {
            name: 'capitalallocationbillno',
            title: '划拨申请单号',
            controlType: 'input',
          },
          {
            name: 'summaryno',
            title: '申请单号',
            controlType: 'input',
          },
          {
            name: 'paymentstatus',
            title: '申请单状态',
            controlType: 'select',
            controlProps: {
              optionsApi: () => {
                return [...drp_paymentstatus]
              },
            },
          },
          {
            name: 'customername',
            title: '再保人',
            controlType: 'input',
          },
          {
            name: 'exchangecurrencycode',
            title: '应付币种',
            controlType: 'select',
            controlProps: {
              optionsApi: () => {
                return [...drp_currency]
              },
            },
          },
          {
            name: 'fastflag',
            title: '加急件',
            controlType: 'select',
            controlProps: {
              optionsApi: () => {
                return [...drop_fastflag]
              },
            },
          },
          {
            name: 'startdate',
            title: '开始日期',
            controlType: 'datePicker',
            controlProps: {
              format: 'YYYY-MM-DD',
              style: { width: '100%' },
            },
          },
          {
            name: 'enddate',
            title: '结束日期',
            controlType: 'datePicker',
            controlProps: {
              format: 'YYYY-MM-DD',
              style: { width: '100%' },
            },
          },

          {
            name: 'payway',
            title: '申请单类型',
            controlType: 'select',
            controlProps: {
              optionsApi: () => {
                return [...drop_payway]
              },
            },
          },
          {
            name: 'custaccountarea',
            title: '境内/外',
            controlType: 'select',
            controlProps: {
              optionsApi: () => {
                return [...drop_domestic]
              },
            },
          },
          {
            name: 'paymentmode',
            title: '支付方式',
            controlType: 'select',
            controlProps: {
              allowClear: false,
              optionsApi: () => {
                return [...drp_type]
              },
            },
            rules: [{ required: true }],
          },
        ],
      },
    }
  },
  created() {
    this.initFun()
  },
  methods: {
    initFun() {
      this.resetData()
      this.getPaymentApplicationFormQueryData()
    },
    resetData() {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.editorsumnum = this.selectedRows.length
      this.editorsumexchangeamount = 0
      this.editorsumamount = 0
    },
    handleFormChange(obj) {
      // console.log('>>>> 表单change:', obj)
      if (obj.name == 'paymentmode') {
        this.activeKey = obj.value == '00' ? '1' : obj.value
        this.initFun()
      }
    },
    async getPaymentApplicationFormQueryData() {
      if (this.loadingTable) return
      this.loadingTable = true
      const res = await getPaymentApplicationFormQueryData({name: 'mike', age: 22})
      console.log('>>> res-mock', res);
      this.loadingTable = false
      this.tableDataSet.clear();
      this.tableDataSource = res?.data?.data || []
      this.tableDataSource.forEach((item) => {
        this.tableDataSet.addRecord(item)
      })
    },
    handleSubmitSuccess() {
      this.initFun()
    },
    handleCancelSelect() {
      this.resetData()
    },
    handlePaymentSuccess() {
      this.initFun()
    },
    handleSelectChange(selectedRowKeys, selectedRows) {
      console.log('>>>>> selectedRows:', selectedRows)
      const flag = selectedRows.find((item) => item.paymentstatus == '7')
      if (flag) return this.$message.warning('已提交支付！')
      for (let i = 0; i < selectedRows.length; i++) {
        const item = selectedRows[i]
        const flag = selectedRows.find(
          (item2) => item2.paymentstatus != item.paymentstatus
        )
        if (flag) return this.$message.warning('申请单类型不一致，请重新选择！')
        const flag2 = selectedRows.find(
          (item2) => item2.exchangecurrencycode != item.exchangecurrencycode
        )
        if (flag2) return this.$message.warning('应付币种不一致，请重新选择！')
      }

      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.editorsumnum = this.selectedRows.length
      this.editorsumexchangeamount = 0
      this.editorsumamount = 0
      if (selectedRows.length < 1) return
      this.selectedRowsExchangecurrencycode =
        selectedRows[0].exchangecurrencycode
      if (this.editorsumnum > 0) {
        this.selectedRows.forEach((item) => {
          this.editorsumexchangeamount += item.exchangeamount
          this.editorsumamount += item.amount
        })
      }
    },
    handleOpenInfo() {
      this.$refs.paymentApplicationFormInfo.handleOpen()
    },
    async handleOpenPDF() {
      this.loadingPDF = true
      // this.$message.warning('没有要查看的PDF！')
      const res = await getPaymentViewPDF()
      this.loadingPDF = false
      if (!res.error) this.$message.success('获取PDF成功！')
    },
    async handleExportFile() {
      if (this.exportFileButtonFlag) return
      const data = this.tableDataSource.filter((item) => item.visible)
      if (data.length < 1) return this.$message.warning('没有要导出的记录！')

      this.exportFileButtonFlag = true
      const res = await getExportFile()
      this.exportFileButtonFlag = false
      if (!res.error) this.$message.success('导出成功！')
    },
    async handleDownFile() {
      if (this.downFileButtonFlag) return
      if (this.selectedRowKeys.length < 1)
        return this.$message.warning('请至少选择一条记录！')
      const data = this.selectedRows.filter((item) => item.paymentstatus != 6)
      if (data.length > 0)
        return this.$message.warning(
          '所选择的数据中有申请单状态不是【待支付】的，请确认数据，重新选择！'
        )
      this.downFileButtonFlag = true
      const res = await getDownPaymentFile()
      this.downFileButtonFlag = false
      if (!res.error) this.$message.success('文件下载成功！')
    },
    handlePaymentInfo() {
      if (this.index == null) return
      this.$refs.paymentWay.handleBankPayment()
    },
    handleReset() {
      this.$refs.queryFormRef.form.resetFields()
      this.$refs.queryFormRef.form.setFieldsValue({
        paymentstatus: '6',
        exchangecurrencycode: '全部',
        payway: '全部',
        paymentmode: '全部',
      })
    },
    async handleSubmit() {
      if (this.submitButtonFlag) return
      const data = this.tableDataSource.filter(
        (item) => item.paymentstatus !== '' && item.paymentstatus !== '10'
      )
      if (data.length > 0)
        return this.$message.warning(
          '查询条件中，申请单状态必须是【待提交】或【全部】时，才可点击点击【提交】按钮！'
        )
      this.submitButtonFlag = true
      const res = await submitPaymentApplicationFormData()
      this.submitButtonFlag = false
      if (!res.error) this.$message.success('提交成功！')
    },
    customRow(record, index) {
      return {
        style: {
          'background-color': index === this.index ? '#e6f7ff' : '',
        },
        on: {
          click: () => {
            this.index = index
            this.nowRecord = record
            this.tableDataSet.currentKey =
              this.tableDataSet.getRecordAt(index).key
            this.$refs.paymentWay.resetTab()
          },
        },
      }
    },
  },
}
</script>

<style scoped lang="less">
.totalInfo {
  position: absolute;
  bottom: 6%;
  width: 50%;
}
</style>